package com.keymozy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keymozy.clients.ImgClient;
import com.keymozy.mapper.MChildMapper;
import com.keymozy.mapper.ModelMapper;
import com.keymozy.mapper.StoreMapper;
import com.keymozy.mapper.ZoneMapper;
import com.keymozy.pojo.MChild;
import com.keymozy.pojo.Model;
import com.keymozy.pojo.Store;
import com.keymozy.pojo.Zone;
import com.keymozy.service.ModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class IModelService extends ServiceImpl<ModelMapper, Model> implements ModelService {
    @Autowired
    private MChildMapper mChildMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ZoneMapper zoneMapper;
    @Value("${image.path}")
    private String imgPath;
    @Autowired
    private ImgClient imgClient;
    @Autowired
    private ModelMapper modelMapper;

    @Transactional
    @Override
    public Map<String, Object> getAll(int currentPage, int pageSize, Model model) {
        log.info("model:"+model);
        Page<Model> p = new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Model> lqw;
        IPage<Model> page;
        if (null!=model){
            lqw  = new LambdaQueryWrapper<>();
            lqw.eq(null!=model.getHeight(),Model::getHeight,model.getHeight());
            lqw.eq(null!=model.getLen(),Model::getLen,model.getLen());
            lqw.eq(null!=model.getWidth(),Model::getWidth,model.getWidth());
            lqw.like(null!=model.getMname()&&!"".equals(model.getMname()),Model::getMname,model.getMname());
            lqw.like(null!=model.getType()&&!"".equals(model.getType()),Model::getType,model.getType());
            lqw.like(null!=model.getMaker()&&!"".equals(model.getMaker()),Model::getMaker,model.getMaker());
            lqw.eq(null!=model.getMaintain(),Model::getMaintain,model.getMaintain());
            lqw.eq(null!=model.getZid(),Model::getZid,model.getZid());
            lqw.eq(null!=model.getProduct()&&!"".equals(model.getProduct()),Model::getProduct,model.getProduct());
            page = page(p,lqw);
            List<Model> records = page.getRecords();
            log.info("过滤后"+records);
        }else{
            page = page(p);
        }
        List<Model> data = page.getRecords();
        if (null==model.getState())
            model.setState(false);
        getChild(data,model.getState());
        Map result = new HashMap();
        result.put("total",page.getTotal());
        result.put("data",data);
        return result;
    }
    private void getChild(List<Model> models,boolean state){
        for (Model model : models) {
            Zone zone = zoneMapper.selectById(model.getZid());
            Store store = storeMapper.selectById(zone.getSid());
            //设置仓库名字
            model.setSzname(store.getSname()+"-"+zone.getSname());
            model.setZone(zone);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(Model model) {
        //添加模具基本信息
        boolean flag = save(model);
        MChild child = new MChild();
        child.setMid(model.getId());
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //将当前时间设置成上一次保养时间
        String time = sdf.format(date);
        log.info("磨具数量"+model);
        child.setTime(time);
        child.setState(0);
        int insert = mChildMapper.insert(child);
        if(insert>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Store> getStore() {
        List<Store> stores = storeMapper.selectList(null);
        for (Store store : stores) {
            LambdaQueryWrapper<Zone> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Zone::getSid,store.getId());
            store.setZones(zoneMapper.selectList(lqw));
        }
        return stores;
    }
    @Transactional
    @Override
    public boolean addNum(Model model) {
        try {
            MChild child = new MChild();
            child.setMid(model.getId());
            child.setState(0);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(date);
            child.setTime(time);

            for (Integer i = 0; i < model.getNum(); i++) {
                mChildMapper.insert(child);
            }
            Model m = getById(model.getId());
            model.setNum(model.getNum()+m.getNum());
            updateById(model);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean alterModel(Model model) {
        boolean flag = updateById(model);
        if (!flag)
            return false;
        return true;
    }

    @Transactional
    @Override
    public boolean deleteModel(Model[] models) {
        log.info("models:"+models);
        for (Model model : models) {
            boolean flag = removeById(model.getId());
            for (MChild child : model.getChildren()) {
                int f = mChildMapper.deleteById(child.getId());
                if (f!=1)
                    return false;
            }
            imgClient.rmImg(this.imgPath+"/model/"+model.getId());
            if (!flag)
                return false;
        }
        return true;
    }

    @Override
    public Map<String, Integer> echartsZone() {
        List<Zone> zones = zoneMapper.selectList(null);
        Map<String, Integer> map = new HashMap<>();
        for (Zone zone : zones) {
            Integer id = zone.getId();
            List<Model> models = modelMapper.selectList(new LambdaQueryWrapper<Model>().eq(Model::getZid, id));
            map.put(zone.getSname(),models.size());
        }
        return map;
    }
}
